package jp.sourceforge.akjrcp.flvtools.explorer;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.akj_betas.imagemagick.ImageMagickCommandUtils;
import jp.sourceforge.akjrcp.commons.ui.widget.WidgetBuilder;
import jp.sourceforge.akjrcp.commons.util.ClipboardUtil;
import jp.sourceforge.akjrcp.commons.util.FileNameUtils;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegCommandUtil;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegFLVParser;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegFileInfomation;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUI;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUtils;
import jp.sourceforge.akjrcp.ffmpeg.SimpleCommandExecuter;
import jp.sourceforge.akjrcp.flvtools.explorer.ExplorerView.CustomFlowLayout;
import jp.sourceforge.akjrcp.tools.OtherToolsSettingPage;
import jp.sourceforge.akjrcp.util.TimeUtils;
import jp.sourceforge.akjrcp.util.image.ImageUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.InputEvent;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.Panel;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

public class ThumnailPreviewWindow extends Dialog {
	public static Log log = LogFactory.getLog(ThumnailPreviewWindow.class);
private String videoPath;
private SelectableFigureList explorerFigure;

private SimpleCommandExecuter executer;
	public ThumnailPreviewWindow(Shell parentShell,String videoPath){
		
		super(parentShell);
		this.videoPath=videoPath;
		
	}
	
	 protected Control createDialogArea(Composite parent) {
		 getShell().setText("");
		    GridData data=new GridData();//for vista//TODO still here is problem
		    data.heightHint=400;
		    data.grabExcessVerticalSpace=true;
		    data.widthHint=680;
		    
		    data.grabExcessHorizontalSpace=true;
		    
		    
		    
		    Composite root=(Composite)super.createDialogArea(parent);
		    
		    root.setLayout(new GridLayout(1,false));
		    
		    
		    Composite controls=new Composite(root,SWT.NULL);
		    controls.setLayout(new GridLayout(3,false));
		    Group s=new Group(controls,SWT.NULL);
		    s.setLayout(new GridLayout(2,false));
		    s.setText(Messages.getString("explorer.saveSingleImage"));
		    //buttons
		    final Button saveSingle=new Button(s,SWT.NULL);
		    saveSingle.setText(Messages.getString("explorer.save"));
		    saveSingle.addSelectionListener(new SelectionListener(){

				@Override
				public void widgetDefaultSelected(SelectionEvent e) {
					
				}

				@Override
				public void widgetSelected(SelectionEvent e) {
					saveSingle.setEnabled(false);
					//getSelectionFigures
					Figure[] figures=explorerFigure.getSelectionFigures();
					for (int i = 0; i < figures.length; i++) {
						ImageAndLabelFigure l=(ImageAndLabelFigure) figures[i];
						try {
							BufferedImage base=ImageIO.read(new File(baseDir,l.getFileName()));
							int[] w_h=FFMpegUtils.sizeToWidthHeight(sizeSingleCombo.getText());
							BufferedImage saveImage=ImageUtils.resizeImage(base, w_h[0], w_h[1]);
							base=null;
							boolean ow=false;
							if(i==0 && overwrite.getSelection()){
								ow=true;
							}
							String path=FileNameUtils.getChangedExtensionName(new File(videoPath), "jpg",ow);
							ImageIO.write(ImageUtils.toRGB(saveImage), "jpg", new File(path));
						} catch (IOException e1) {
							// TODO �����������ꂽ catch �u���b�N
							e1.printStackTrace();
						}
					}
					saveSingle.setEnabled(true);
					 canvas.setFocus();
					}
		    	
		    });
		    sizeSingleCombo = new CCombo(s,SWT.NULL);
			sizeSingleCombo.add("320x240");
		    sizeSingleCombo.add("640x480");
		    sizeSingleCombo.add("160x120");
		    sizeSingleCombo.add("120x90");
		    sizeSingleCombo.add("125x125");
		    sizeSingleCombo.select(0);
		  
		    
		    Group saveListGroup=new Group(controls,SWT.NULL);
		    saveListGroup.setLayout(new GridLayout(4,false));
		    saveListGroup.setText(Messages.getString("explorer.saveList"));
		    
		    final Button saveList=new Button(saveListGroup,SWT.NULL);
		    saveList.setText(Messages.getString("explorer.save"));
		    if(Akj_betasPlugin.getDefault().getPluginPreferences().getString(OtherToolsSettingPage.PATH_IMAGEMAGICK_MONTAGE).equals("")){
		    	saveList.setEnabled(false);   
		    }
		    saveList.addSelectionListener(new SelectionListener(){

				@Override
				public void widgetDefaultSelected(SelectionEvent e) {
					
				}

				@Override
				public void widgetSelected(SelectionEvent e) {
					saveList.setEnabled(false);
					String montagePath=Akj_betasPlugin.getDefault().getPluginPreferences().getString(OtherToolsSettingPage.PATH_IMAGEMAGICK_MONTAGE);
					//getSelectionFigures
					Figure[] figures=explorerFigure.getSelectionFigures();
					if(figures.length==0){
						return;
					}
					String output=FileNameUtils.getChangedExtensionName(new File(videoPath), "jpg",overwrite.getSelection());
					File tmp=null;
					try {
						tmp=File.createTempFile("thums", ".jpg");
					} catch (IOException e1) {
						// TODO �����������ꂽ catch �u���b�N
						e1.printStackTrace();
					}
					List<String> inputs=new ArrayList<String>();
					for (int i = 0; i < figures.length; i++) {
						ImageAndLabelFigure l=(ImageAndLabelFigure) figures[i];
						
							inputs.add(baseDir+"\\"+l.getFileName());
							
					
					}
					String size=sizeListCombo.getText();
					int[] w_h=FFMpegUtils.sizeToWidthHeight(size);
					int cols=Integer.parseInt(sizeListXCombo.getText());
					int rows=Integer.parseInt(sizeListYCombo.getText());
					String command[]=ImageMagickCommandUtils.makeMontageCommand(montagePath, inputs.toArray(new String[inputs.size()]), tmp.getAbsolutePath(), w_h[0], w_h[1], cols, rows);
					 executer=new SimpleCommandExecuter(command);
					 Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(FFMpegUtils.toPrintCommand(command)+"\n");
					 
					 //flv file info
					 executer.setPrinter(Akj_betasPlugin.getDefault().getProcessPrinter());
					 executer.execute();
					 int page=inputs.size()/(cols*rows);
					 if(inputs.size()%(cols*rows)>0){
						 page++;
					 }
					 log.trace(page);
					 if(page==1){
						 boolean b=tmp.renameTo(new File(output));//jp seems not supported
					 }else{
						 String baseName=FileNameUtils.getRemovedExtensionName(tmp.getName());
						 
						for(int i=0;i<page;i++){
							File pageFile=new File(tmp.getParent(),baseName+"-"+i+"."+FileNameUtils.getExtension(tmp.getName()));
							//log.trace(pageFile.getAbsolutePath());
							if(pageFile.exists()){
								 String outBaseName=FileNameUtils.getRemovedExtensionName(output);
							//	 log.trace(outBaseName+"-"+i+".jpg");
								 boolean b=pageFile.renameTo(new File(outBaseName+"-"+i+".jpg"));//jp seems not supported
							}
						}
					 }
					 saveList.setEnabled(true);
					 canvas.setFocus();
					}
		    	
		    });
		    
		    sizeListCombo = new CCombo(saveListGroup,SWT.NULL);
		    sizeListCombo.add("160x120");
		    sizeListCombo.add("320x240");
		    sizeListCombo.add("100x75");
		    sizeListCombo.add("80x40");
		    sizeListCombo.add("160x90");
		    sizeListCombo.select(0);
		    
		    String listSize=Akj_betasPlugin.getDefault().getPluginPreferences().getString(ExplorerImageMagickPage.IMAGE_LIST_SIZE);
		   if(listSize.length()>0){
			   sizeListCombo.setText(listSize);
		   }
		    
		    int cols=Akj_betasPlugin.getDefault().getPluginPreferences().getInt(ExplorerImageMagickPage.IMAGE_LIST_W);
			int rows=Akj_betasPlugin.getDefault().getPluginPreferences().getInt(ExplorerImageMagickPage.IMAGE_LIST_H);
			
		    sizeListXCombo = new CCombo(saveListGroup,SWT.NULL);
		    int selectCols=0;
		    for (int i = 1; i <= 10; i++) {
		    	sizeListXCombo.add(""+i);
		    	if(i==cols){
		    		selectCols=i-1;
		    	}
			}
		    sizeListXCombo.select(selectCols);
		    
		    sizeListYCombo = new CCombo(saveListGroup,SWT.NULL);
		    int selectRows=0;
		    for (int i = 1; i <= 10; i++) {
		    	sizeListYCombo.add(""+i);
		    	if(i==rows){
		    		selectRows=i-1;
		    	}
			}
		    sizeListYCombo.select(selectRows);
		    
		    
		    //GIF
		    Group saveGifGroup=new Group(controls,SWT.NULL);
		    saveGifGroup.setLayout(new GridLayout(7,false));
		    saveGifGroup.setText(Messages.getString("explorer.saveGif"));
		    
		    final Button saveGif=new Button(saveGifGroup,SWT.NULL);
		    saveGif.setText(Messages.getString("explorer.save"));
		    saveGif.addSelectionListener(new SelectionListener(){

				@Override
				public void widgetDefaultSelected(SelectionEvent e) {
					
				}

				@Override
				public void widgetSelected(SelectionEvent e) {
					saveGif.setEnabled(false);
					log.info("start make gifanime");
					String convertPath=Akj_betasPlugin.getDefault().getPluginPreferences().getString(OtherToolsSettingPage.PATH_IMAGEMAGICK_CONVERT);
					//getSelectionFigures
					Figure[] figures=explorerFigure.getSelectionFigures();
					if(figures.length==0){
						log.info("no figure selected");
						return;
					}
					String output=FileNameUtils.getChangedExtensionName(new File(videoPath), "gif",overwrite.getSelection());
					File tmp=null;
					try {
						tmp=File.createTempFile("thums", ".gif");
					} catch (IOException e1) {
						// TODO �����������ꂽ catch �u���b�N
						e1.printStackTrace();
					}
					List<String> inputs=new ArrayList<String>();
					for (int i = 0; i < figures.length; i++) {
						ImageAndLabelFigure l=(ImageAndLabelFigure) figures[i];
						
							inputs.add(baseDir+"\\"+l.getFileName());
							
					
					}
					
					String size=sizeGifCombo.getText();
					int[] w_h=FFMpegUtils.sizeToWidthHeight(size);
					int loop=Integer.parseInt(sizeGifLoopCombo.getText());
					int wait=Integer.parseInt(sizeGifWaitCombo.getText());
					
					
					String command[]=ImageMagickCommandUtils.makeGifAnimeCommand(convertPath, inputs.toArray(new String[inputs.size()]), tmp.getAbsolutePath(), w_h[0], w_h[1], wait,loop);
					 log.info(FFMpegUtils.toPrintCommand(command));
					executer=new SimpleCommandExecuter(command);
					
					 Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(FFMpegUtils.toPrintCommand(command)+"\n");
					 
					 
					 executer.setPrinter(Akj_betasPlugin.getDefault().getProcessPrinter());
					 executer.execute();
					 
					 boolean renamed=tmp.renameTo(new File(output));
					 if(!renamed){
						 log.warn("gifanime rename faild:"+output);
					 }else{
						 log.info("gif anime renamed:"+output);
					 }
					 saveGif.setEnabled(true);
					 canvas.setFocus();
				}
		    });
		    
		    overwrite = new Button(controls,SWT.CHECK);
			overwrite.setText(Messages.getString("thumnailmake.overwrite"));
		    if(Akj_betasPlugin.getDefault().getPluginPreferences().getString(OtherToolsSettingPage.PATH_IMAGEMAGICK_CONVERT).equals("")){
		    	saveGif.setEnabled(false);   
		    }
		    
		    canvas = new FigureCanvas(root);
			canvas.setLayoutData(data);
			//canvas.setLayoutData(new GridData(GridData.FILL_BOTH));
		    
		    Figure rootFigure = new Figure();
		    rootFigure.setLayoutManager(new StackLayout());
			canvas.setContents(rootFigure);
			canvas.addKeyListener(new KeyListener(){

				public void keyPressed(KeyEvent e) {
					
				}

				public void keyReleased(KeyEvent e) {
					
					if(e.stateMask == SWT.CTRL && e.keyCode==97){
						explorerFigure.selectAll();
					}
				}
				
			});
			
			Menu canvasPopup = new Menu(canvas);
			canvas.setMenu(canvasPopup);
			MenuItem selectAll = new MenuItem(canvasPopup, SWT.PUSH);
			selectAll.setText(Messages.getString("explorer.select_all"));
			selectAll.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					explorerFigure.selectAll();
				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}

			});
			
			MenuItem copyTime = new MenuItem(canvasPopup, SWT.PUSH);
			copyTime.setText(Messages.getString("explorer.copy_time"));
			copyTime.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					Figure[] fs=explorerFigure.getSelectionFigures();
					if(fs.length>0){
						String label=((ImageAndLabelFigure)fs[0]).getLabel();
						ClipboardUtil.setClipboard(ThumnailPreviewWindow.this.getShell().getDisplay(), label);
					}
				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}

			});
			
			sizeGifCombo = new CCombo(saveGifGroup,SWT.NULL);
			sizeGifCombo.add("320x240");
			sizeGifCombo.add("160x120");
			sizeGifCombo.add("100x75");
			sizeGifCombo.add("80x40");
			sizeGifCombo.add("640x480");
			sizeGifCombo.add("160x90");
			sizeGifCombo.select(0);
		    
		   
		    
		    String animeSize=Akj_betasPlugin.getDefault().getPluginPreferences().getString(ExplorerImageMagickPage.GIF_ANIME_SIZE);
			   if(animeSize.length()>0){
				   sizeGifCombo.setText(animeSize);
			   }
		    int loop=Akj_betasPlugin.getDefault().getPluginPreferences().getInt(ExplorerImageMagickPage.GIF_ANIME_LOOP);
			int wait=Akj_betasPlugin.getDefault().getPluginPreferences().getInt(ExplorerImageMagickPage.GIF_ANIME_WAIT);
		    
			WidgetBuilder.createLabel(saveGifGroup, Messages.getString("explorer.loop"));
			sizeGifLoopCombo = new CCombo(saveGifGroup,SWT.NULL);
		    int selectLoop=0;
		    for (int i = 0; i <= 3; i++) {
		    	sizeGifLoopCombo.add(""+i);
		    	if(i==loop){
		    		selectLoop=i;
		    	}
			}
		    sizeGifLoopCombo.select(selectLoop);
		    
		    WidgetBuilder.createLabel(saveGifGroup, Messages.getString("explorer.wait"));
		    sizeGifWaitCombo = new CCombo(saveGifGroup,SWT.NULL);
		    int selectWait=0;
		    for (int i = 0; i <= 5; i++) {
		    	sizeGifWaitCombo.add(""+(i*50));
		    	if(i*50==wait){
		    		selectWait=i;
		    	}
		    }
		    sizeGifWaitCombo.select(selectWait);
			
			explorerFigure = new SelectableFigureList();
			explorerFigure.setBackgroundColor(ColorConstants.white);
			explorerFigure.setLayoutManager(new CustomFlowLayout(canvas,rootFigure));
			rootFigure.add(explorerFigure);
			
			
		    //start parsing.
			
			 File dir=new File(baseDir);
			 dir.mkdir();
			 try {
				FileUtils.cleanDirectory(dir);
				
			} catch (IOException e) {
				// TODO �����������ꂽ catch �u���b�N
				e.printStackTrace();
			}
			
			VideoThumbsCreater videoThumbs=new VideoThumbsCreater();
			videoThumbs.start();
			
			ImageChecker imageChecker=new ImageChecker();
			videoThumbs.setImageChecker(imageChecker);
			imageChecker.start();
		    
			canvas.setFocus();
	        return root;
	    }
	 
	 public class LabelAndName extends Label{
		 private String name;

		public LabelAndName(Image createThumbnail) {
			super(createThumbnail);
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
		 
	 }

	 public static class SelectableFigureList extends Panel{
			LineBorder selectedBorder; 
			MarginBorder notSelectedBorder;
			Figure lastSelected;
			public SelectableFigureList(){
				selectedBorder = new LineBorder();
				selectedBorder.setColor(ColorConstants.green);
				selectedBorder.setWidth(2);
				
				notSelectedBorder=new MarginBorder(2);
				this.setBorder(notSelectedBorder);
				
				addMouseListener(new MouseListener() {

					

					public void mousePressed(org.eclipse.draw2d.MouseEvent mouseEvent) {
						List list=getChildren();
						Figure selected=null;
						for (int i = 0; i < list.size(); i++) {
							Figure f=(Figure) list.get(i);
							if(f.getBounds().contains(mouseEvent.x, mouseEvent.y)){
								selected=f;
								break;
							}
						}
						
						if(selected!=null){
							
						
						
						if(mouseEvent.button==1){//left click
						if((mouseEvent.getState() & InputEvent.CONTROL)>0){
							
							setSelection(selected,!isSelection(selected));
						}else if((mouseEvent.getState() & InputEvent.SHIFT)>0){
							//
							selectBetween(selected);
						}else{
							boolean last=!isSelection(selected);
							unselectAll();
							
							setSelection(selected,last);
							
						}
						}else if(mouseEvent.button==3){//right click
							
						}
						
						lastSelected=selected;
						}
						
					}

					public void mouseReleased(MouseEvent arg0) {
						
					}

					public void mouseDoubleClicked(MouseEvent event){
							

					}

				});
			}
			
			private void selectBetween(Figure selected){
				int lastIndex=0;
				int selectedIndex=0;
				List list=getChildren();
				
				for (int i = 0; i < list.size(); i++) {
					Figure f=(Figure) list.get(i);
					if(f==selected){
						selectedIndex=i;
						
					}
					if(lastSelected!=null && f==lastSelected){
						lastIndex=i;
					}
				}
				int start,end;
				if(lastIndex>selectedIndex){
					start=selectedIndex;
					end=lastIndex;
				}else{
					start=lastIndex;
					end=selectedIndex;
				}
				
				for(int i=start;i<=end;i++){
					setSelection(((Figure)list.get(i)),true);
				}
				
			}
			private void unselectAll(){
				List list=getChildren();
				
				for (int i = 0; i < list.size(); i++) {
					Figure f=(Figure) list.get(i);
					setSelection(f,false);
				}
			}
			
			public void selectAll(){
				List list=getChildren();
				
				for (int i = 0; i < list.size(); i++) {
					Figure f=(Figure) list.get(i);
					setSelection(f,true);
				}
			}
			
			public Figure[] getSelectionFigures(){
				List<Figure> list=new ArrayList<Figure>();
				Figure figures[]=(Figure[]) this.getChildren().toArray(new Figure[0]);
				//log.infofigures:"+figures.length);
				for (int i = 0; i < figures.length; i++) {
					
						
						if(isSelection(figures[i])){
						list.add(figures[i]);
						}
					
					
				}
				return  list.toArray(new Figure[0]);
			}
			
			public void addFigure(Figure figure){
				setSelection(figure,false);
				add(figure);
				
				this.repaint();
			}
			
			public boolean isSelection(Figure figure){
				return figure.getBorder()!=null && figure.getBorder()==selectedBorder;
			}
			
			public void setSelection(Figure figure,boolean bool){
				
				
				if(bool){
					
					figure.setBorder(selectedBorder);
				}else{
					figure.setBorder(notSelectedBorder);
				}
				figure.repaint();
				
			}
		}
	 
	 double  fps = 1;
	 public class VideoThumbsCreater extends Thread{
		 private IImageChecker imageChecker;
	
		 
		 public void run(){
			
			 String ffmpeg=FFMpegUI.getFFmpegOrPureFFMpeg();
			 if(ffmpeg==null){
				 return;
			 }
			 FFMpegFLVParser parser=new FFMpegFLVParser(ffmpeg);
			 FFMpegFileInfomation info=parser.parseFile(new File(videoPath));
			 double time=FFMpegUtils.timeToDouble(info.getDuration());
			
			if(time>0){
				 fps=30/time;	//can castomize
			 }
			
			 //BUG min rate not supported
			if(fps<0.25){
				fps=0.25;//for error [mjpeg @ 007C2B30]bitrate tolerance too small for bitrate
			}
			 String rates[]={"-r",""+fps};
			 log.info("fps:"+fps);
			  executer=new SimpleCommandExecuter(FFMpegCommandUtil.makeJpegOutputFileCommand(ffmpeg, videoPath, baseDir+baseName+"%5d"+"."+extension, rates));
			 //flv file info
			 executer.setPrinter(Akj_betasPlugin.getDefault().getProcessPrinter());
			 executer.execute();
			 
			//simple process executer.
			 
			 //call execute
			 //get duration and set fps and make
			 //done=true
		 }

		public IImageChecker getImageChecker() {
			return imageChecker;
		}

		public void setImageChecker(IImageChecker imageChecker) {
			this.imageChecker = imageChecker;
		}
	 }
	 
	 public interface IImageChecker{
		 public void setDone(boolean done);
	 }
	 
	 public static String baseDir="temporary/thumbs/";
	 private String baseName="videothumbs";
	 private String extension="jpg";
	 private CCombo sizeSingleCombo;
	 private CCombo sizeListCombo;
	 private CCombo sizeListXCombo;
	 private CCombo sizeListYCombo;
	 private CCombo sizeGifCombo;
	 private CCombo sizeGifWaitCombo;
	 private CCombo sizeGifLoopCombo;
	private Button overwrite;
	private FigureCanvas canvas;
	 public class ImageChecker extends Thread implements IImageChecker{
		 private boolean done;
		 private boolean cancelled;
		
		
		 private int index=1;
		 private long timeout=1000*60*10;//10minute
		
		 public void run(){
			 Display display=getShell().getDisplay();
			 LOOP:while(!cancelled){
				 String numStr=FileNameUtils.digited(index,5);
				 String fileName=baseName+numStr+"."+extension;
				 File file=new File(baseDir,fileName);
				 long lasttime=System.currentTimeMillis();
				 if(file.exists()){
					 Image img=new Image(null,file.getAbsolutePath());
					 //TODO make thumbnail
					 long time=(long) ((1/fps)*(index-1));
					 String label=TimeUtils.toTimeText(time*1000,true,true,true,false);
					 ImageAndLabelFigure figure=new ImageAndLabelFigure(label,ImageUtils.createThumbnail(img, 160, 120));
					 figure.setFileName(fileName);
					/*
					 LabelAndName label=new LabelAndName(ImageUtils.createThumbnail(img, 160, 120));
					 label.setName(fileName);//for get
					 img.dispose();
					 */
					 
					 display.syncExec(new AddFigure(explorerFigure,figure));
					// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay().syncExec(new AddFigure(explorerFigure,label));
					 index++;
					 lasttime=System.currentTimeMillis();
				 }else{
					 if(lasttime+timeout<System.currentTimeMillis()){
						 break LOOP;//timeout break;
					 }
					 
					 if(done){
						 log.trace("done");
						 break;
					 	}
					 try {
						Thread.sleep(250);
					} catch (InterruptedException e) {
						// TODO �����������ꂽ catch �u���b�N
						e.printStackTrace();
					}
				 }
			 }
			 //check dir
			
			
			 //progress bar ..sync
			 //add figure
		 }
		public boolean isDone() {
			return done;
		}
		public void setDone(boolean done) {
			this.done = done;
		}

	 }

	 
	 
	 //TODO figureUtils
	 public static class AddFigure extends Thread{
		 private SelectableFigureList parent;
		 private Figure figure;
		 public AddFigure(SelectableFigureList parent,Figure figure){
			 this.parent=parent;
			 this.figure=figure;
		 }
		 public void run(){
			 parent.addFigure(figure);
			 parent.revalidate();//?
		 }
	 }
	 
	 protected void createButtonsForButtonBar(Composite parent) {
		    
		    createButton(
		      parent,
		      IDialogConstants.CLOSE_ID,
		      IDialogConstants.CLOSE_LABEL,
		      true);
		   
		  }
	 
	 protected void buttonPressed(int id) {
		   
		    if (id == IDialogConstants.CLOSE_ID) {
		      setReturnCode(id);
		      //cancel making.
		      if(executer!=null){
		    	  executer.cancel();
		      }
		      
		      try {
					FileUtils.cleanDirectory(new File(baseDir));
					
				} catch (IOException e) {
					//sometime error happen if process doing.
					log.trace("sometime happen when process still doing");
					e.printStackTrace();
				}
				
		      close();
		    }
		    
		    super.buttonPressed(id);
		  }

}
